package cn.ciis.basic.websocket;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import com.baomidou.kisso.SSOHelper;

import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
import javax.websocket.server.ServerEndpointConfig.Configurator;
import java.util.List;
import java.util.Map;

/**
 * @author 冉志林
 * @description
 * @date 3/14/2019
 */
public class GetCookieConfigurator extends Configurator {

  @Override
  public void modifyHandshake(
      ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
    Map<String, List<String>> headers = request.getHeaders();
    List<String> cookieList = headers.get("Cookie");
    Map<String,String> kv = MapUtil.newHashMap();
    if(CollUtil.isNotEmpty(cookieList)) {
      String cookieStr = cookieList.get(0);
      String[] cookieArray = cookieStr.split("; ");
      for(String cookie : cookieArray){
        String[] cookieKv = cookie.split("=");
        if(cookieKv.length <2){
          continue;
        }
        kv.put(cookieKv[0], cookieKv[1]);
      }
    }
    String sessionId = kv.get(SSOHelper.getSsoConfig().getCookieName());
    sec.getUserProperties().put(String.class.getName(),sessionId);
  }
}
